<template>
  <div class="login-container">
    <div class="container">
      <div class="login-content">
        <div class="login-left">
          <div class="brand-section">
            <h1 class="brand-name">在线教育平台</h1>
            <p class="brand-slogan">学习不止，进步不停</p>
            <div class="features">
              <div class="feature-item">
                <el-icon class="feature-icon">
                  <VideoPlay/>
                </el-icon>
                <span>优质课程</span>
              </div>
              <div class="feature-item">
                <el-icon class="feature-icon">
                  <User/>
                </el-icon>
                <span>专业教师</span>
              </div>
              <div class="feature-item">
                <el-icon class="feature-icon">
                  <Star/>
                </el-icon>
                <span>学习进度</span>
              </div>
            </div>
          </div>
        </div>
        <div class="login-right">
          <div class="login-wrapper">
            <h2 class="login-title">用户登录</h2>
            <p class="login-subtitle">欢迎回来，请登录您的账号</p>

            <!-- 登录方式切换标签 -->
            <div class="login-tabs">
              <el-tabs v-model="activeTab" class="login-tabs">
                <el-tab-pane label="账号密码登录" name="password"></el-tab-pane>
                <el-tab-pane label="手机验证码登录" name="sms"></el-tab-pane>
              </el-tabs>
            </div>

            <el-form ref="loginFormRef" :model="loginForm" :rules="rules" label-width="0" class="login-form">
              <!-- 账号密码登录方式 -->
              <template v-if="activeTab === 'password'">
                <el-form-item prop="username">
                  <el-input v-model="loginForm.username" placeholder="请输入用户名" prefix-icon="User"/>
                </el-form-item>
                <el-form-item prop="password">
                  <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" prefix-icon="Lock"
                            show-password/>
                </el-form-item>
                <el-form-item>
                  <el-checkbox v-model="loginForm.rememberMe">记住我</el-checkbox>
                </el-form-item>
              </template>

              <!-- 手机验证码登录方式 -->
              <template v-if="activeTab === 'sms'">
                <el-form-item prop="phone">
                  <el-input v-model="loginForm.phone" placeholder="请输入手机号" prefix-icon="Phone"/>
                </el-form-item>
                <el-form-item prop="verificationCode">
                  <el-input v-model="loginForm.verificationCode" placeholder="请输入验证码" prefix-icon="Key">
                    <template #append>
                      <el-button
                          :disabled="countdown > 0"
                          @click="sendVerificationCode"
                          :loading="sendingCode"
                          type="text"
                      >
                        {{ countdown > 0 ? `${countdown}秒后重发` : '获取验证码' }}
                      </el-button>
                    </template>
                  </el-input>
                </el-form-item>
              </template>

              <el-form-item>
                <el-button type="primary" @click="handleLogin" :loading="loading" class="login-btn">登录</el-button>
              </el-form-item>
              <div class="login-footer">
                <span>还没有账号？</span>
                <router-link to="/register" class="register-link">立即注册</router-link>
              </div>
            </el-form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, reactive} from 'vue'
import {useRouter, useRoute} from 'vue-router'
import {ElMessage} from 'element-plus'
import {VideoPlay, User, Star, Phone, Key} from '@element-plus/icons-vue'
import {sendCode} from "@/api/SendMsg.js";
import {userLogin} from "@/api/Users.js";

const router = useRouter()
const route = useRoute()
const loginFormRef = ref(null)
const loading = ref(false)
const activeTab = ref('password') // 当前激活的登录方式标签
const countdown = ref(0) // 验证码倒计时
const sendingCode = ref(false) // 发送验证码按钮加载状态

const loginForm = reactive({
  username: '',
  password: '',
  rememberMe: false,
  phone: '',
  verificationCode: ''
})

const rules = {
  username: [
    {
      required: true, message: '请输入用户名', trigger: 'blur', validator: (rule, value, callback) => {
        if (activeTab.value === 'password') {
          if (!value) {
            callback(new Error('请输入用户名'))
          } else if (value.length < 3 || value.length > 20) {
            callback(new Error('用户名长度在 3 到 20 个字符'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
    }
  ],
  password: [
    {
      required: true, message: '请输入密码', trigger: 'blur', validator: (rule, value, callback) => {
        if (activeTab.value === 'password') {
          if (!value) {
            callback(new Error('请输入密码'))
          } else if (value.length < 6) {
            callback(new Error('密码长度至少为 6 个字符'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
    }
  ],
  phone: [
    {
      required: true, message: '请输入手机号', trigger: 'blur', validator: (rule, value, callback) => {
        if (activeTab.value === 'sms') {
          const phoneRegex = /^1[3-9]\d{9}$/
          if (!value) {
            callback(new Error('请输入手机号'))
          } else if (!phoneRegex.test(value)) {
            callback(new Error('请输入正确的手机号码'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
    }
  ],
  verificationCode: [
    {
      required: true, message: '请输入验证码', trigger: 'blur', validator: (rule, value, callback) => {
        if (activeTab.value === 'sms') {
          const codeRegex = /^\d{6}$/
          if (!value) {
            callback(new Error('请输入验证码'))
          } else if (!codeRegex.test(value)) {
            callback(new Error('请输入6位数字验证码'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
    }
  ]
}

// 发送验证码
const sendVerificationCode = async () => {
  // 验证手机号
  const phoneValid = await new Promise((resolve) => {
    rules.phone[0].validator(null, loginForm.phone, (err) => {
      resolve(!err)
      if (err) {
        ElMessage.error(err.message)
      }
    })
  })

  if (!phoneValid) return

  sendingCode.value = true
  try {
    // 模拟发送验证码API调用
    setTimeout(() => {
      sendCode(loginForm.phone).then(res => {
        if (res.code === 200) {
          ElMessage.success('验证码已发送，请注意查收')
        }
      })
      sendingCode.value = false
      // 开始倒计时
      countdown.value = 60
      const timer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    }, 1000)
  } catch (error) {
    sendingCode.value = false
    ElMessage.error('发送验证码失败，请稍后重试')
    console.error('发送验证码失败:', error)
  }
}

// 处理登录
const handleLogin = async () => {
  try {
    await loginFormRef.value.validate()
    loading.value = true
    // 根据登录方式调用不同的登录逻辑
    if (activeTab.value === 'password') {
      // 账号密码登录 - 模拟API调用
      setTimeout(() => {
        const mockUserInfo = {
          id: 1,
          username: loginForm.username,
          name: '测试用户',
          isAdmin: loginForm.username === 'admin'
        }
        const mockToken = 'mock_token_' + Date.now()
        // 保存登录状态
        localStorage.setItem('token', mockToken)
        localStorage.setItem('userInfo', JSON.stringify(mockUserInfo))
        if (loginForm.rememberMe) {
          localStorage.setItem('rememberedUsername', loginForm.username)
        } else {
          localStorage.removeItem('rememberedUsername')
        }
        ElMessage.success('登录成功')
        // 处理重定向
        handleRedirect()
      }, 1000)
    } else if (activeTab.value === 'sms') {
      // 手机验证码登录
      userLogin({
        phone: loginForm.phone
        , code: loginForm.verificationCode
      }).then(res => {
        if (res.code === 200) {
          console.log(res)
          // 保存登录状态
          sessionStorage.setItem('token', res.data.token)
          //存储用户信息
          sessionStorage.setItem("userInfo", JSON.stringify(res.data.userInfo))
          ElMessage.success('登录成功')
          // 处理重定向
          handleRedirect()
        } else {
          ElMessage.error(res.msg)
          loading.value = false
        }
      })
    }
  } catch (error) {
    console.error('登录验证失败:', error)
    loading.value = false
  }
}

// 处理登录后的重定向
const handleRedirect = () => {
  // 优先从localStorage获取重定向路径（用于购买流程）
  const redirectAfterLogin = sessionStorage.getItem('redirectAfterLogin')
  let redirectPath = ''
  if (redirectAfterLogin) {
    // 如果存在重定向路径，使用它并删除存储的路径
    redirectPath = redirectAfterLogin
    sessionStorage.removeItem('redirectAfterLogin')
  } else {
    // 否则使用URL参数或默认到首页
    redirectPath = route.query.redirect || '/home'
  }

  router.push(redirectPath)
}

// 页面加载时检查是否有记住的用户名
const rememberedUsername = localStorage.getItem('rememberedUsername')
if (rememberedUsername) {
  loginForm.username = rememberedUsername
  loginForm.rememberMe = true
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  display: flex;
  align-items: center;
}

.container {
  max-width: 1200px;
  width: 100%;
  margin: 0 auto;
}

.login-content {
  display: flex;
  background: white;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
  overflow: hidden;
}

.login-left {
  flex: 1;
  padding: 60px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.brand-name {
  font-size: 36px;
  font-weight: bold;
  margin-bottom: 16px;
}

.brand-slogan {
  font-size: 18px;
  margin-bottom: 40px;
  opacity: 0.9;
}

.features {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.feature-item {
  display: flex;
  align-items: center;
  gap: 16px;
}

.feature-icon {
  font-size: 24px;
  background: rgba(255, 255, 255, 0.2);
  padding: 12px;
  border-radius: 50%;
}

.login-right {
  flex: 1;
  padding: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.login-wrapper {
  width: 100%;
  max-width: 400px;
}

.login-title {
  color: #303133;
  margin-bottom: 8px;
  font-size: 28px;
}

.login-subtitle {
  color: #606266;
  margin-bottom: 20px;
  font-size: 16px;
}

.login-tabs {
  margin-bottom: 20px;
}

.login-tabs .el-tabs__header {
  margin: 0 0 20px 0;
}

.login-tabs .el-tabs__nav-wrap::after {
  background-color: #ebeef5;
}

.login-form .el-form-item {
  margin-bottom: 24px;
}

.login-form .el-input__wrapper {
  border-radius: 8px;
}

.login-btn {
  width: 100%;
  padding: 12px;
  font-size: 16px;
  border-radius: 8px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}

.login-footer {
  display: flex;
  justify-content: center;
  margin-top: 24px;
  font-size: 14px;
  color: #606266;
}

.register-link {
  color: #667eea;
  margin-left: 5px;
  text-decoration: none;
}

.register-link:hover {
  color: #5a6fd8;
  text-decoration: underline;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-content {
    flex-direction: column;
  }

  .login-left {
    padding: 40px;
    text-align: center;
  }

  .login-right {
    padding: 40px 20px;
  }

  .features {
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: center;
    gap: 20px;
  }

  .feature-item {
    flex-direction: column;
    text-align: center;
  }

  .login-tabs {
    margin-bottom: 15px;
  }

  .login-tabs .el-tabs__header {
    margin: 0 0 15px 0;
  }
}
</style>